import store from '../../stores/index'
function pickJsonObj(value) {
    try {
        var msg = value.replace(String.fromCharCode(0x1e), ""); //替换消息结束符					
        return JSON.parse(msg);
    } catch (e) {
        return null;
    }
}

class WebSocketClient {
    constructor(url) {
        this.url = url;
        this.socket = null;
        this.isReconnecting = false;
        this.reconnectInterval = 15000; // 重连间隔，单位毫秒
        this.heartBeatInterval = 15000; // 心跳间隔，单位毫秒
        this.pingTimeoutDuration = 1000 * 60; // 超过这个时间，后端没有返回pong，则判定后端断线了。
        this.heartBeatTimer = null;
        this.destroy = false; // 是否销毁
    }

    connect() {
        if(this.socket){
            this.socket.close();
            this.socket = null;
        }
        this.socket = uni.connectSocket({
            url: this.url,
            complete: () => { }
        });
        this.initEventListeners();
    }

    initEventListeners() {
        this.socket.onOpen(() => {
            // WebSocket连接已打开
            this.onConnected();
            const datas = `{"protocol":"json", "version":1}${String.fromCharCode(
                0x1e,
            )}`
            this.sendMessage(datas)
            // 心跳机制
            this.startHeartBeat();
            // 开始断线检测
            this.startpingTimeout()
            store.commit('setSocket', true)
        });

        this.socket.onMessage((res) => {
            const obj = pickJsonObj(res.data);
            console.log(obj, '我是obj信息')
            if (obj.type === 6) {
                // 收到pong消息，心跳正常，无需处理
                this.startpingTimeout(); // 重置计时
            } else {
                // 处理其他消息
                this.onMessage(obj);
            }
        });

        this.socket.onClose((res) => {
            console.error('WebSocket连接不正常关闭已关闭', res)
            // WebSocket连接已关闭
            if (this.destroy) {
                this.onClosed()
                return;
            }
            // 关闭心跳
            this.stopHeartBeat();
            if (!this.isReconnecting) {
                this.reconnect();
            }
        });
    }

    sendMessage(message) {
        if (this.socket) {
            this.socket.send({
                data: message
            });
        }
    }

    onMessage(message) {
        // 处理收到的消息
        console.log('message:', message)
    }
    // 设置心跳检测
    startHeartBeat() {
        if (this.heartBeatTimer) {
            clearInterval(this.heartBeatTimer);
        }
        this.heartBeatTimer = setInterval(() => {
            this.sendMessage(JSON.stringify({
                type: 6,
            })); // 发送ping消息
            // this.pingTimeout = setTimeout(() => {
            //     // 未收到pong消息，尝试重连...
            //     this.reconnect();
            //     console.error('我一分钟后没有检测到有ping我重新链接了')
            // }, this.pingTimeoutDuration);
            console.log('发送心跳包')
        }, this.heartBeatInterval);
    }
    // 超时检测
    startpingTimeout() {
        // 如果收到了消息就重置断线时间
        if (this.pingTimeout) {
            clearTimeout(this.pingTimeout); // 重置计时
        }
        this.pingTimeout = setTimeout(() => {
            // 未收到pong消息，尝试重连...
            this.reconnect();
            console.error('我一分钟后没有检测到有ping我重新链接了')
        }, this.pingTimeoutDuration);
    }
    // 关闭心跳检测
    stopHeartBeat() {
        if (this.heartBeatTimer) {
            clearInterval(this.heartBeatTimer);
        }
    }
    // 重新连接
    reconnect() {
        this.isReconnecting = true;
        store.commit('setSocket', false)
        setTimeout(() => {
            this.onReconnect();
            this.connect();
            this.isReconnecting = false;
        }, this.reconnectInterval);
    }

    close() {
        this.destroy = true;
        this.stopHeartBeat();
        if (this.socket) {
            this.socket.close();
            this.socket = null;
        }
    }
    /**
     * 重连时触发
     */
    onReconnect() {
        console.log('尝试重连...')
    }
    /**
     * 连接成功时触发
     */
    onConnected() {
        console.log('WebSocket连接已打开');
    }
    /**
     * 断开时触发
     */
    onClosed() {
        console.log('已断开连接')
    }
}

export default WebSocketClient;
